import json
import os

from flask import render_template, Blueprint, request, jsonify, session, redirect, url_for

from service import restaurant
from util.request_helper import get_parameter, get_cookie_jar

restaurant_list = Blueprint('restaurant_list', __name__)


@restaurant_list.route("/shop")
def shop():
    latitude = get_parameter(request, 'latitude')
    longitude = get_parameter(request, 'longitude')
    address = get_parameter(request, 'address')
    page = get_parameter(request, 'page')
    if page is None:
        page = 1
    # session中存好经纬度可在详情页使用
    session['latitude'] = latitude
    session['longitude'] = longitude
    cookie = session.get("cookie")
    if cookie is None:
        # 说明没登录，判断是否有cookie文件，如果有就读入cookie，没有则跳转登录页
        if os.path.exists("cookie.txt"):
            with open("cookie.txt", 'r') as f:
                cookie = json.load(f)
        else:
            # 保存好当前的url，方便在登陆后直接跳转过来
            session['redirect_url'] = "http://" + request.host + request.path + "?" \
                                      + str(request.query_string, encoding="utf-8")
            return redirect(url_for('login.login_page'))
    cookie_jar = get_cookie_jar(cookie)
    res = restaurant.request_restaurant_list(cookie_jar, latitude, longitude, (int(page) - 1) * 16)
    if res is None:
        return jsonify({"message": "IP被限制，请更换IP地址再试"})
    else:
        telephone = session.get("telephone")
        if telephone is None:
            if os.path.exists("telephone.txt"):
                with open("telephone.txt", "r") as f:
                    telephone = f.readline()
            else:
                return redirect(url_for('login.login_page'))
        base_info = {
            'telephone': telephone,
            'address': address
        }
        return render_template('shop.html', res=res, info=base_info)
